import React from 'react';
import { NewsColumns, ProductColumns, PublicationColumns } from './content';
import { Button, Space, Table } from 'antd';
import { useRequest } from 'ahooks';
import { useParams } from '../../hooks/useParams';
import EditorFormModal from '../EditorForm';
import './index.less';
import { deleteNew } from '../../services/news';

/** 页面类型 */
type PageType = 'products' | 'news' | 'publications';

interface IProps {
  type: PageType
}

const EditorContent: React.FC<IProps> = ({ type }) => {
  /** 第几页 */
  const [pageNo, setPageNo] = React.useState(1);
  /** 总数 */
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(5);
  const [data, setData] = React.useState([]);
  const { type: pageType = 'KEYAN' } = useParams();
  /** 表单 */
  const [formStatus, setFormStatus] = React.useState<'create' | 'edit'>('create');
  const [formOpen, setFormOpen] = React.useState<boolean>(false);
  const [formData, setFormData] = React.useState<any>();

  const { run: getProducts } = useRequest(async (type: string, page: number, size: number) => {
    const res = await fetch(`http://localhost:7001/api/products/all?pageNo=${page}&pageSize=${size}`, {
      method: 'get',
    })
    return res.json();
  }, {
    manual: true,
    onSuccess: (res) => {
      const resData = res.data.map((item: { uuid: string }) => ({ ...item, key: item.uuid }));
      setTotal(res.total);
      setData(resData);
    }
  });

  const { run: getPublication } = useRequest(async (page: number, size: number) => {
    const res = await fetch(`http://localhost:7001/api/publication/all?pageNo=${page}&pageSize=${size}`, {
      method: 'get',
    })
    return res.json();
  }, {
    manual: true,
    onSuccess: (res) => {
      const resData = res.data.map((item: { uuid: string }) => ({ ...item, key: item.uuid }));
      setTotal(res.total);
      setData(resData);
    }
  })

  const { run: getNews } = useRequest(async (page: number, size: number) => {
    const res = await fetch(`http://localhost:7001/api/news/detailByType?type=${pageType}&pageNo=${page}&pageSize=${size}`, {
      method: 'get',
    })
    return res.json();
  }, {
    manual: true,
    onSuccess: (res) => {
      const resData = res.data.map((item: { uuid: string }) => ({ ...item, key: item.uuid }));
      setTotal(res.total);
      setData(resData);
    }
  })

  // 初始状态
  React.useEffect(() => {
    getNews(1, 5);
  }, [pageType]);

  /** 编辑函数 */
  const handleEdit = React.useCallback((record: any) => {
    setFormData(record);
    setFormOpen(true);
  }, [type]);

  /** 删除函数 */
  let handleDelete = React.useCallback((record: any) => {
    switch (type) {
      case 'news':
        deleteNew({
          uuid: record.uuid
        }).then(res => {
          getNews(pageNo, pageSize);
        });
      case 'products':
        return () => { };
      case 'publications':
        return () => { };
      default:
        return () => { };
    }
  }, [type]);

  const getColumns = React.useCallback((type: PageType) => {
    const actions = {
      title: '操作',
      render: (_: any, record: any) => {
        return <Space>
          <Button onClick={() => handleEdit(record)} type='primary'>编辑</Button>
          <Button onClick={() => handleDelete(record)} danger>删除</Button>
        </Space>
      }
    }
    switch (type) {
      case 'news':
        return [...NewsColumns, actions];
      case 'products':
        return [...ProductColumns, actions];
      case 'publications':
        return [...PublicationColumns, actions];
      default:
        return [];
    }
  }, [handleEdit, handleDelete]);

  const columns = getColumns(type);

  const handleCreate = () => {
    setFormOpen(true);
  }

  return (
    <div className='editor-content-container'>
      <Button type='primary' style={{ marginBottom: '16px' }} onClick={() => handleCreate()}>新增</Button>
      <Table
        dataSource={data}
        columns={columns}
        pagination={{
          current: pageNo,
          pageSize,
          total,
          onChange: (page: number, size: number) => {
            getNews(page, size);
            setPageNo(page);
            setPageSize(size);
          }
        }}
      ></Table>
      <EditorFormModal
        data={formData}
        open={formOpen}
        status={formStatus}
        type={type}
        onModalFinish={() => {
          setFormOpen(false);
        }}
      />
    </div>
  )
}

export default EditorContent;